package com.xxp.controller;


import cn.hutool.core.collection.CollUtil;
import com.xxp.common.Result;
import com.xxp.controller.request.AdminPageRequest;
import com.xxp.controller.request.BaseRequest;
import com.xxp.controller.request.CategoryRequest;
import com.xxp.entity.Category;
import com.xxp.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/category")
@CrossOrigin
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    @GetMapping("/page")//分页模糊查询
    public Result page(CategoryRequest baseRequest){
        return Result.success(categoryService.listByCondition(baseRequest));
    }


    @GetMapping("/tree")
    public Result treeList(){
        List<Category> list = categoryService.list();
        //null表示从第一级开始递归
        return Result.success(createTree(null,list));
    }
    /**
     *使用递归
     */
    private List<Category> createTree(Integer pid,List<Category> categories){
        List<Category> treeList=new ArrayList<>();
        for (Category category : categories) {
            if (pid==null){
                //如果传进来的Pid为null并且遍历的pid也为null，说明就是一级节点
                if (category.getPid()==null){
                    treeList.add(category);
                    //设置子节点并自己调用自己进行递归
                    category.setChildren(createTree(category.getId(),categories));
                }
            }else{
                if (pid.equals(category.getPid())){
                    treeList.add(category);
                    category.setChildren(createTree(category.getId(),categories));
                }
            }
            if (CollUtil.isEmpty(category.getChildren())){
                category.setChildren(null);
            }

        }

        return treeList;
    }


    @PostMapping("/add")
    public Result save(@RequestBody Category category){
        //自关联
        categoryService.save(category);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Category category = categoryService.getById(id);
        return  Result.success(category);
    }
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        categoryService.deleteById(id);
        return Result.success();
    }
    @PutMapping("/update")
    public Result update(@RequestBody Category category){
        categoryService.update(category);
        return Result.success();
    }
}
